package com.by.yz.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.android.volley.toolbox.NetworkImageView;
import com.bumptech.glide.Glide;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.activity.FeedbackActivity;
import com.by.yz.activity.PersonalEditActivity;
import com.by.yz.activity.QuestionDetail;
import com.by.yz.activity.QuikListActivity;
import com.by.yz.activity.SettingActivity;
import com.by.yz.chatuidemo.Constant;
import com.by.yz.chatuidemo.DemoHelper;
import com.by.yz.chatuidemo.db.InviteMessgeDao;
import com.by.yz.chatuidemo.ui.MainActivity;
import com.by.yz.chatuidemo.ui.UserProfileActivity;
import com.by.yz.common.MFGT;
import com.by.yz.custom.CircleNetworkImageView;
import com.by.yz.entity.Account;
import com.by.yz.entity.UserTest;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.UserRESTFul;
import com.by.yz.mypersonal.PersonalDoctorActivity;
import com.by.yz.mypersonal.PersonalRestDoctor;
import com.by.yz.util.ToJSonObject;
import com.hyphenate.EMMessageListener;
import com.hyphenate.EMValueCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.domain.EaseUser;

import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * “我的”碎片页面
 * @author wwj_748
 *
 */
public class personalCenterFragment extends Fragment implements View.OnClickListener {

	private CircleNetworkImageView networkImageView;//个人头像
	private View view;
	private RelativeLayout problem;
	private RelativeLayout answer;
	private RelativeLayout community;
	private RelativeLayout contract;
	private RelativeLayout setting;
	private RelativeLayout feedback;
	private Button doctor;
	private Button reset;
	private Toast toast;
	TextView login;
	Account account;
	UserTest userTest;
	private TextView unreadLabel;
	private TextView unreadAddressLable;
	private InviteMessgeDao inviteMessgeDao;
	private LocalBroadcastManager broadcastManager;
	private BroadcastReceiver broadcastReceiver;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.personal_center_fragment, container,
				false);
		//initDatas();
		//initView();
		return view;
	}

	@Override
	public void onResume(){
		Log.e("调用onResume()","onResume");
		super.onResume();
		initView();
		initDatas();
		updateUnreadAddressLable();
		updateUnreadLabel();
		registerBroadcastReceiver();
		EMClient.getInstance().chatManager().addMessageListener(messageListener);
	}

	private void initView() {
		Log.e("调用initView()","111");
		//个人头像
		networkImageView = (CircleNetworkImageView) view.findViewById(R.id.headerPicture);
		//置该控件默认时显示的图片
		networkImageView.setDefaultImageResId(R.mipmap.login_logo1);
		//设置加载网络图片失败时显示的图片
		networkImageView.setErrorImageResId(R.mipmap.login_error);
		//从网络上加载图片
//		networkImageView.setImageUrl("http://img2.hao661.com/uploads/allimg/c150515/1431E91Z5M10-2194c1.jpg",App.imageLoader);

		networkImageView.setOnClickListener(this);
		// 登录名
		login=(TextView) view.findViewById(R.id.personalName) ;
		// 我的问题
		problem = (RelativeLayout) view.findViewById(R.id.pc_my_problem);
		problem.setOnClickListener(this);
		// 我的回答
		answer = (RelativeLayout) view.findViewById(R.id.pc_my_answer);
		answer.setOnClickListener(this);
		// 我的社区
		community = (RelativeLayout) view.findViewById(R.id.pc_my_community);
		community.setOnClickListener(this);
		// 我的联系人
		contract = (RelativeLayout) view.findViewById(R.id.pc_my_contract);
		contract.setOnClickListener(this);
		// 设置与帮助
		setting = (RelativeLayout) view.findViewById(R.id.pc_my_setting);
		setting.setOnClickListener(this);
		// 意见反馈
		feedback = (RelativeLayout) view.findViewById(R.id.pc_my_feedback);
		feedback.setOnClickListener(this);
		// 申请医生
		doctor = (Button) view.findViewById(R.id.ApplyDoctor);
		doctor.setOnClickListener(this);
		// 修改资料
		reset = (Button) view.findViewById(R.id.reset_date);
		reset.setOnClickListener(this);

		unreadLabel = (TextView) view.findViewById(R.id.PCFunread_msg_number);
		unreadAddressLable = (TextView) view.findViewById(R.id.unread_address_number);
		inviteMessgeDao = new InviteMessgeDao(view.getContext());
	}

	private void initDatas() {
		Log.e("调用initDatas()","222");
		AccountRESTFul accountRESTFul=new AccountRESTFul();
		accountRESTFul.get(new AccountRESTFul.IhttpCb() {
			@Override
			public void ok(JSONObject response) {
				account=ToJSonObject.jsonToBean( response.toString(),Account.class);
				UserRESTFul userRESTFul=new UserRESTFul();
				userRESTFul.getUser(account.getLogin(), new UserRESTFul.UserPOSTCallBack() {
					@Override
					public void ok(JSONObject response) throws JSONException {
						userTest=ToJSonObject.jsonToBean(response.toString(),UserTest.class);
						login.setText(userTest.getnickName());
						if(userTest.getHeadimg()!=null){
							networkImageView.setImageUrl(userTest.getHeadimg(), App.imageLoader);
						}
						if(userTest.getflag()){
							problem.setVisibility(View.GONE);
							doctor.setVisibility(View.GONE);
							answer.setVisibility(View.VISIBLE);
							reset.setVisibility(View.VISIBLE);
						}
					}
					@Override
					public void error(String response) {
						Log.e("PCF-user-error","获取用户表失败"+response);
					}
				});
			}

			@Override
			public void error(String error) {
				Log.e("PCF-account-error","授权失败"+error);
			}
		});
	}

	@Override
	public void onClick(View v) {

		Context context = v.getContext();
		switch (v.getId()) {

			case R.id.headerPicture:
				Intent intent=new Intent(context,UserProfileActivity.class);
				Bundle bundle=new Bundle();
				bundle.putSerializable("user",userTest);
				intent.putExtras(bundle);
				intent.putExtra("setting", true);
				intent.putExtra("username", EMClient.getInstance().getCurrentUser());
				context.startActivity(intent);
				break;

			case R.id.pc_my_problem:
				Intent intent1=new Intent(context,QuikListActivity.class);
				intent1.putExtra("isDoctor", false);
				intent1.putExtra("username", EMClient.getInstance().getCurrentUser());
				context.startActivity(intent1);
				break;

			case R.id.pc_my_answer:
				Intent intent2=new Intent(context,QuikListActivity.class);
				intent2.putExtra("isDoctor", true);
				intent2.putExtra("username", EMClient.getInstance().getCurrentUser());
				context.startActivity(intent2);
				break;

			case R.id.pc_my_community:{
				if(toast != null){
					toast.setText("努力策划中，敬请期待...");
					toast.setDuration(Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 0);
					toast.show();
				}
				else{
					toast = Toast.makeText(getActivity(), "努力策划中，敬请期待...", Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 0);
					toast.show();
				}
				break;
			}

			case R.id.pc_my_contract:
				MFGT.startActivity(getActivity(), MainActivity.class);
				break;

			case R.id.pc_my_setting:
//				MFGT.startActivity(getActivity(), SettingActivity.class);
				Intent intent5=new Intent(this.getActivity(),SettingActivity.class);
				intent5.putExtra("myPhone", userTest.getPhonenumber());
				context.startActivity(intent5);
				break;

			case R.id.pc_my_feedback:
				MFGT.startActivity(getActivity(), FeedbackActivity.class);
				break;

			case R.id.ApplyDoctor:
				Intent intent3=new Intent(this.getActivity(),PersonalDoctorActivity.class);
				Bundle bundle3=new Bundle();
				bundle3.putSerializable("applydoctor",userTest);
				intent3.putExtras(bundle3);
				startActivity(intent3);
//				MFGT.startActivity(getActivity(),PersonalDoctorActivity.class);
				break;

			case R.id.reset_date:
				Intent intent4=new Intent(this.getActivity(),PersonalRestDoctor.class);
				Bundle bundle2=new Bundle();
				bundle2.putSerializable("resetdoctor",userTest);
				intent4.putExtras(bundle2);
				startActivity(intent4);
//				MFGT.startActivity(getActivity(),PersonalDoctorActivity.class);
				break;
		}
	}
	private void registerBroadcastReceiver() {
		broadcastManager = LocalBroadcastManager.getInstance(this.getActivity());
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constant.ACTION_CONTACT_CHANAGED);
		intentFilter.addAction(Constant.ACTION_GROUP_CHANAGED);
		//intentFilter.addAction(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION);
		broadcastReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				updateUnreadLabel();
				updateUnreadAddressLable();
			}
		};
		broadcastManager.registerReceiver(broadcastReceiver, intentFilter);
	}

	/**
	 * update unread message count
	 */
	public void updateUnreadLabel() {
		Log.e("调用updateUnreadLabel()","个人中心333");
		int count = getUnreadMsgCountTotal();
		if (count > 0) {
			if(count > 99){
				unreadLabel.setText(99+"+");
			}else {
				unreadLabel.setText(String.valueOf(count));
			}
			Log.e("显示未读信息数",count+"条");
			unreadLabel.setVisibility(View.VISIBLE);
		} else {
			unreadLabel.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * update the total unread count
	 */
	public void updateUnreadAddressLable() {
		Log.e("调用updateUnreadAddress()","个人中心444");
//		runOnUiThread(new Runnable() {
//			public void run() {
				int count = getUnreadAddressCountTotal();
				if (count > 0) {
					Log.e("显示未读请求的小圆点",count+"个");
					unreadAddressLable.setVisibility(View.VISIBLE);
				} else {
					unreadAddressLable.setVisibility(View.INVISIBLE);
				}
//			}
//		});
	}

	/**
	 * get unread event notification count, including application, accepted, etc
	 *
	 * @return
	 */
	public int getUnreadAddressCountTotal() {
		int unreadAddressCountTotal = 0;
		unreadAddressCountTotal = inviteMessgeDao.getUnreadMessagesCount();
		return unreadAddressCountTotal;
	}

	/**
	 * get unread message count
	 *
	 * @return
	 */
	public int getUnreadMsgCountTotal() {
		int unreadMsgCountTotal = 0;
		int chatroomUnreadMsgCount = 0;
		unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
		for(EMConversation conversation:EMClient.getInstance().chatManager().getAllConversations().values()){
			if(conversation.getType() == EMConversation.EMConversationType.ChatRoom)
				chatroomUnreadMsgCount=chatroomUnreadMsgCount+conversation.getUnreadMsgCount();
		}
		return unreadMsgCountTotal-chatroomUnreadMsgCount;
	}

	EMMessageListener messageListener = new EMMessageListener() {

		@Override
		public void onMessageReceived(List<EMMessage> messages) {
			// notify new message
			for (EMMessage message : messages) {
				DemoHelper.getInstance().getNotifier().onNewMsg(message);
			}
			refreshUIWithMessage();
		}

		@Override
		public void onCmdMessageReceived(List<EMMessage> messages) {}

		@Override
		public void onMessageReadAckReceived(List<EMMessage> messages) {}

		@Override
		public void onMessageDeliveryAckReceived(List<EMMessage> list) {}

		@Override
		public void onMessageChanged(EMMessage message, Object change) {}
	};

	private void refreshUIWithMessage() {
//		runOnUiThread(new Runnable() {
//			public void run() {
				// refresh unread count
				updateUnreadLabel();
				Log.e("收到信息","个人中心收到完毕");
//			}
//		});
	}

}